package com.yxq.mdt.app.utils;

import com.yxq.mdt.app.base.RespBase;
import com.yxq.mdt.app.modules.order.bean.UploadImageResultBean;
import com.yxq.mdt.app.net.API;
import com.yxq.mdt.app.net.BaseObserver;
import com.yxq.mdt.app.net.FastJsonConverterFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * @author L
 * @time 2019-11-11
 * @describe 图片上传工具$
 */
public class ImageUploader {

    private int i = 0;//图片序号
    private int taskCount = 0;//总任务数
    private Map<Integer, RespBase<UploadImageResultBean>> respBaseMap;//图片上传返回对象
    private ImageUploaderInterface imageUploaderInterface;

    public void setImageUploaderInterface(ImageUploaderInterface imageUploaderInterface) {
        this.imageUploaderInterface = imageUploaderInterface;
    }

    /**
     * 图片上传回调
     */
    public interface ImageUploaderInterface {
        /**
         * 返回上传结果
         *
         * @param response 返回图片上传返回对象 按照上传的循序排序
         */
        void onResponse(List<RespBase<UploadImageResultBean>> response);
    }


    public void addRespBaseMap(int position, RespBase<UploadImageResultBean> respBase) {
        if (this.respBaseMap == null) {
            this.respBaseMap = new HashMap<Integer, RespBase<UploadImageResultBean>>();
        }
        respBaseMap.put(position, respBase);
        if (taskCount == respBaseMap.size()) {
            if (imageUploaderInterface != null) {
                imageUploaderInterface.onResponse(getRespBaseList());
            }
        }
    }

    public List<RespBase<UploadImageResultBean>> getRespBaseList() {
        List<RespBase<UploadImageResultBean>> respBaseList = new ArrayList<>();
        for (int i = 0; i < taskCount; i++) {
            respBaseList.add(respBaseMap.get(Integer.valueOf(i)));
        }
        return respBaseList;
    }

    /**
     * 上传多张图
     *
     * @param compressFile 图片文件集合(建议先压缩后再上传)
     */
    public void uploadImages(List<File> compressFile) {
        if (compressFile == null) {
            return;
        }
        taskCount = compressFile.size();


        if (compressFile != null && !compressFile.isEmpty()) {

            for (i = 0; i < compressFile.size(); i++) {

                File file = compressFile.get(i);

                uploadImage(i, file);
            }
        }
    }

    private void uploadImage(int position, File file) {
        //多张图片
        Map<String, RequestBody> map = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);

        map.put("image\"; filename=\"" + file.getName(), requestBody);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(API.HOST_PHP)
                .addConverterFactory(FastJsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        retrofit.create(ApiService.class)
                .uploadImages(map)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<RespBase<UploadImageResultBean>>() {
                    @Override
                    public void onFailure(Throwable e, boolean isNetWorkError) {
                        RespBase respBase = new RespBase<>();
                        respBase.setCode(-1);
                        respBase.setMsg(e != null ? e.getMessage() : "");
                        addRespBaseMap(position, respBase);
                    }

                    @Override
                    public void onSuccess(RespBase<UploadImageResultBean> respBase) {
                        addRespBaseMap(position, respBase);
                    }
                });
    }
}
